import { contextBridge, desktopCapturer, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)

    contextBridge.exposeInMainWorld('electronAPI', {
      getScreenSource: async () => {
        const source = await ipcRenderer.invoke('get-screen-source')
        return source
      },
      // ⚡ 接收 ArrayBuffer，转成 Node Buffer 再发
      saveVideo: (arrayBuffer) => {
        const buffer = Buffer.from(arrayBuffer)
        ipcRenderer.send('save-video', buffer)
      },
      onSaveSuccess: (callback) => ipcRenderer.on('save-video-success', (_, path) => callback(path))
    })
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}
